<template>
  <div class="original-site-table">
    <div class="header">
      <div v-if="isWeight" class="label w-[240px]">权重</div>
      <div
        class="label min-w-[326px] flex-1"
        :class="{ '!w-446px': !isWeight }">
        域名/IP
      </div>
      <div
        class="label min-w-[326px] flex-1"
        :class="{ '!w-446px': !isWeight }">
        端口
      </div>
      <div class="label w-[64px]">操作</div>
    </div>
    <div class="container">
      <source-site
        v-for="(item, index) in sourceList"
        :key="item.uuid"
        ref="refs"
        v-model:priority="item.priority"
        v-model:host="item.host"
        v-model:port="item.port"
        :disable-delete="sourceList.length === 1"
        :primary="isWeight && index === 0"
        @priority-change="validate(['priority'])"
        @host-change="validate(['host'])"
        @delete="sourceList.splice(index, 1)"></source-site>
    </div>
    <div class="footer" @click="appendSource">
      <i-icons-table-add /> 添加一行
    </div>
  </div>
</template>

<script setup lang="ts">
import { v4 as uuidV4 } from 'uuid'

import { A_PRIORITY_TYPE } from '@/constants/site'
import SourceSite from './SourceSite.vue'
import type { ISourceSite } from './types'

interface IEmit {
  (event: 'update:list', value: ISourceSite[]): void
}

interface IProps {
  list: ISourceSite[]
  algorithm: string
}

const emit = defineEmits<IEmit>()
const props = defineProps<IProps>()

const refs = ref()
const sourceList = useVModel(props, 'list', emit)
const isWeight = computed(() => props.algorithm === A_PRIORITY_TYPE.WEIGHT)
// 添加一个新源站
function appendSource() {
  sourceList.value.push({
    uuid: uuidV4(),
    priority: +sourceList.value[sourceList.value.length - 1].priority + 1,
    host: '',
    port: null
  })
}
function reset() {
  sourceList.value = [{ uuid: uuidV4(), priority: 1, host: '', port: null }]
}
function validate(fields?: string[]) {
  return Promise.all(refs.value.map((item) => item.validate(fields)))
}

provide('sourceList', sourceList)
provide('priorityType', toRef(props, 'algorithm'))

defineExpose({ validate, reset })
</script>

<style scoped lang="less">
.original-site-table {
  @apply rounded-2 w-full min-w-952px overflow-hidden;
  border: 1px solid #dfe2e5;
  .header {
    @apply h-12 py-1.5 flex items-center bg-[#F8F9FA];
    .label {
      @apply text-3 text-sm/22px px-4 font-700;
      &:last-child {
        @apply mr-0;
      }
    }
  }
  .container {
    @apply max-h-60 overflow-auto;
  }
  .footer {
    @apply h-12 flex-center text-sm/22px gap-x-6px text-primary cursor-pointer border border-t-solid border-color-#DFE2E5;
  }
}
</style>
